package com.jerei.web.utils.ui;

import com.jerei.utils.UtilsCommon;
import freemarker.core.Environment;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

/**
 * Created by sunfeihu on 2016/11/11.
 */
@Component
public class ScriptForAllTag implements TemplateDirectiveModel {

    @Autowired
    private HttpServletRequest request;

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        String end = UtilsCommon.getString(params.get("end"));
        String scriptUrl = request.getServletPath();
        if ("".equals(scriptUrl)) {
            return;
        }
        if (null != end && !"".equals(end)) {
            scriptUrl = scriptUrl.substring(0, scriptUrl.lastIndexOf("/")) + "/" + end + ".js";
        } else {
            scriptUrl = scriptUrl + ".js";
        }
        Locale locale = request.getLocale();
        String lang = "zh";
        if (null != locale) {
            lang = locale.getLanguage();
        }
        scriptUrl = "/resources/js/" + lang + scriptUrl;
        env.setLocalVariable("scriptUrl", new SimpleScalar(scriptUrl));
        Writer out = env.getOut();
        if (body != null) {
            body.render(env.getOut());
        } else {
            throw new RuntimeException("标签内部至少要加一个空格");
        }
    }
}